package com.jic.product.impl;

import com.alibaba.fastjson.JSONArray;
import com.beust.jcommander.internal.Lists;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.base.vo.enums.DeptTypeEnums;
import com.jic.common.utils.IDUtils;
import com.jic.manager.api.manage.SysDeptApi;
import com.jic.manager.request.SysDeptRequest;
import com.jic.manager.response.MemStoreResponse;
import com.jic.manager.response.MerchantResponse;
import com.jic.manager.response.SysDeptResponse;
import com.jic.market.api.after.MarketApi;
import com.jic.market.api.rest.RealTimePriceRestApi;
import com.jic.market.request.PromotionPolymericRequest;
import com.jic.market.request.rest.groupon.GrouponInfoRequest;
import com.jic.market.response.PromotionPolymericProductResponse;
import com.jic.market.response.PromotionPolymericResponse;
import com.jic.market.response.PromotionSingleProductResponse;
import com.jic.market.response.rest.groupon.GrouponInfoResponse;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.request.MeStoreListRequest;
import com.jic.product.after.request.ProductSaleNumRequest;
import com.jic.product.after.request.SaveProductRequest;
import com.jic.product.after.response.*;
import com.jic.product.common.util.BeanUtil;
import com.jic.product.entity.*;
import com.jic.product.manage.request.*;
import com.jic.product.manage.response.*;
import com.jic.product.mapper.*;
import com.jic.product.rest.request.ProductRestRequest;
import com.jic.product.rest.response.*;
import com.jic.product.service.*;
import com.jic.product.store.request.MStoreFrozenRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 商品表
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-01-10 07:03:01
 */
@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private SysDeptApi sysDeptApi;

    @Resource
    private ProductBomMapper productBomMapper;

    @Resource
    private ProductGuaranteeRelationMapper productGuaranteeRelationMapper;

    @Resource
    private ProductPriceMapper productPriceMapper;

    @Resource
    private ProductGuaranteeRelationService productGuaranteeRelationService;

    @Resource
    private ProductDistributeService productDistributeService;

    @Resource
    private ProductPriceService productPriceService;

    @Resource
    private ProductDescribeService productDescribeService;

    @Resource
    private ProductAfterSaleService productAfterSaleService;

    @Resource
    private ProductPropertyNameRelationService productPropertyNameRelationService;

    @Resource
    private ProductPropertyValueRelationService productPropertyValueRelationService;

    @Resource
    private ProductSaleAreaRelationService productSaleAreaRelationService;

    @Resource
    private ProductMediaService productMediaService;

    @Resource
    private ProductMediaMapper productMediaMapper;

    @Resource
    private ProductPriceAuditMapper productPriceAuditMapper;

    @Resource
    private StoreInventoryMapper storeInventoryMapper;

    @Resource
    private ProductDistributeMapper productDistributeMapper;

    @Resource
    private ProductCalibrationMapper productCalibrationMapper;

    @Resource
    private CategoryTreeNodeRelationMapper categoryTreeNodeRelationMapper;

    @Resource
    private CategoryTreeNodeProductMapper categoryTreeNodeProductMapper;

    @Resource
    private BrandManagementMapper brandManagementMapper;

    @Resource
    private CategoryMerchantRelationService categoryMerchantRelationService;


    @Resource
    private RealTimePriceRestApi realTimePriceRestApi;

    @Resource
    private MarketApi marketApi;






    @Override
    public List<ProductResponse> queryProductCatalog(Product product) {
        return productMapper.queryProductCatalog(product);
    }


    @Override
    public long updateShopCansale(Product product) {
        return productMapper.updateShopCansale(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<Product> addProductInfo(Product product, long[] guaranteeId) {

        if (product.getId() > 0) {
            productMapper.update(product);
            //更新操作先删除所有商品保障
            productGuaranteeRelationMapper.deleteProductGuarantee(product.getId());
        } else {
//            if (StringUtils.equals("B2C", product.getChannelCode()) || StringUtils.equals("B2B", product.getChannelCode())) {
//                List<MemStoreResponse> memStoreResponseList = sysDeptApi.getStoreInfo().getData();
//                if (CollectionUtils.isEmpty(memStoreResponseList)) {
//                    return RestResult.error("9999", "配置失败,店铺不存在");
//                }
//                if (memStoreResponseList.size() > 1) {
//                    return RestResult.error("9999", "配置失败,店铺存在多个");
//                }
//                product.setDeptId(memStoreResponseList.get(0).getDeptId());
//            }
            product.setCode(IDUtils.GenerateBillNo("P"));
        }
        productMapper.insertAndGetId(product);
        //保存商品保障关联
        for (int i = 0; i < guaranteeId.length; i++) {
            ProductGuaranteeRelation productGuaranteeRelation = new ProductGuaranteeRelation();
            BeanUtils.copyProperties(product, productGuaranteeRelation);
            productGuaranteeRelation.setGuaranteeId(guaranteeId[i]);
            productGuaranteeRelation.setProductId(product.getId());
            productGuaranteeRelationMapper.insert(productGuaranteeRelation);
        }

        return RestResult.success(product);
    }

    @Override
    public RestResult<Boolean> addProductPriceInfo(Product product, long[] guaranteeId) {
        if (product.getId() > 0) {
            productMapper.update(product);
            //更新操作先删除所有商品保障
            productGuaranteeRelationMapper.deleteProductGuarantee(product.getId());
        } else {
            product.setCode(IDUtils.GenerateBillNo("P"));
            productMapper.insert(product);
        }
        //保存商品保障关联
        for (int i = 0; i < guaranteeId.length; i++) {
            ProductGuaranteeRelation productGuaranteeRelation = new ProductGuaranteeRelation();
            BeanUtils.copyProperties(product, productGuaranteeRelation);
            productGuaranteeRelation.setGuaranteeId(guaranteeId[i]);
            productGuaranteeRelation.setProductId(product.getId());
            productGuaranteeRelationMapper.insert(productGuaranteeRelation);
        }

        return RestResult.success(true);
    }

    @Override
    public long delete(Long id) {
        return productMapper.delete(id);
    }

    @Override
    public long update(Product product) {
        return productMapper.update(product);
    }

    @Override
    public Product queryByPrimaryKey(Long id) {
        return productMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<Product> query(Product product) {
        return productMapper.query(product);
    }

    @Override
    public List<Product> queryProductInfoByParentId(Product product) {
        return productMapper.queryProductInfoByParentId(product);
    }

    @Override
    public PageResult<ProductResponse> queryPage(Product product, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<ProductResponse> list = productMapper.queryPage(startIndex, pageQuery.getLimit(), product);
        SysDeptRequest sysDeptRequest = new SysDeptRequest();
        list.forEach(item ->{
            sysDeptRequest.setId(item.getDeptId());
            RestResult<MerchantResponse> merchantByDeptId = sysDeptApi.getMerchantByDeptId(sysDeptRequest);
            if(merchantByDeptId.getData() != null){
                item.setMerchantCode(merchantByDeptId.getData().getOrgNumber());
                item.setMerchantName(merchantByDeptId.getData().getName());
            }


            List<Category> categories = categoryMapper.queryById(item.getCategoryId());
            
            
            if(categories.size()>0){
                
                
                item.setFullNamePath(categories.get(0).getName());
            }
            


        });
        long count = productMapper.queryPageCount(product);
        //存储商品类目值
        
        
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public PageResult<ShopInfoResponse> queryShopPage(ShopInfoRequest shop, Page pageQuery) {
        DeptTypeEnums deptType = shop.getAdminOperate().getDeptType();
        if (deptType.getCode() == 0) {
            shop.getAdminOperate().setDeptId(null);
        }
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();

        List<Long> storeIds = shop.getStoreIds();
        if (CollectionUtils.isNotEmpty(storeIds)) {
            List<Long> businessIds = storeIds;
            Integer deptType1 = DeptTypeEnums.STORE_PLATFORM.getCode();
            log.info("businessIds:{}", businessIds);
            RestResult<List<Long>> deptIdsByStroreIdOrMerchantIdAndType = sysDeptApi.getDeptIdsByStroreIdOrMerchantIdAndType(businessIds, deptType1);
            log.info("queryDepidsRest === deptIds:{}", JSONArray.toJSONString(deptIdsByStroreIdOrMerchantIdAndType));
            if (CollectionUtils.isNotEmpty(deptIdsByStroreIdOrMerchantIdAndType.getData())) {
                shop.setDeptIds(StringUtils.join(deptIdsByStroreIdOrMerchantIdAndType.getData(), ","));
                shop.getAdminOperate().setDeptId(null);
                shop.setTypeOfProduct(2);
            }
        }
        List<ShopInfoResponse> list = productMapper
                .queryShopPage(startIndex, pageQuery.getLimit(), shop);
        list.forEach(item -> {
            if (item != null && item.getTypeOfProduct() == 2) {
                List<Product> productList = productMapper.queryProductByParentId(new Product() {{
                    setParentId(item.getId());
                }});
                if (CollectionUtils.isNotEmpty(productList)) {
                    List<Long> list1 = new ArrayList<>();
                    productList.forEach(item1 -> {
                        list1.add(item1.getId());
                    });
                    Integer integer = storeInventoryMapper.queryByProductIds(list1);
                    item.setTotalStock(integer);
                }
            }

            List<SysDeptResponse> deptList = sysDeptApi.query(new SysDeptRequest() {{
                setId(item.getDeptId());
            }});
            if (CollectionUtils.isNotEmpty(deptList)) {
                item.setStoreId(deptList.get(0).getBusinessId());
                item.setStoreName(deptList.get(0).getDeptName());
                List<SysDeptResponse> pDeptList = sysDeptApi.query(new SysDeptRequest() {{
                    setId(deptList.get(0).getPid());
                }});
                if (CollectionUtils.isNotEmpty(pDeptList)) {
                    item.setDeptId(pDeptList.get(0).getBusinessId());
                    item.setDeptName(pDeptList.get(0).getDeptName());
                }
            }
        });
        long count = productMapper.queryShopCount(shop);
        PageResult<ShopInfoResponse> pageResult = new PageResult<ShopInfoResponse>();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public ShopInfoResponse getShopInfo(ShopInfoRequest shop){
        return productMapper.getShopInfo(shop);
    }

    @Override
    public List<ProductResponseFront> queryRecommendedProducts() {
        return productMapper.queryRecommendedProducts();
    }

    @Override
    public List<ProductPropertyResponseFront> queryProductsPropertyById(long id) {
        //返回结果集
        List<ProductPropertyResponseFront> list = new ArrayList<>();
        //查询商品
        Product product = productMapper.queryByPrimaryKey(id);
        //查询商品基本信息
        ProductResponseFront productResponseFront = productMapper.getProductInfoById(product.getId());
        //判断是普通商品还是系列品
        if (product.getTypeOfProduct() == 2) {
            //根据系列虚品的Id 查询所有子商品
            product.setParentId(product.getId());
            List<Product> products = productMapper.query(product);
            if(CollectionUtils.isNotEmpty(products)){
                //重新封装数组
                Long[] ids = new Long[products.size()];
                for (int i = 0; i < ids.length; i++) {
                    ids[i] = products.get(i).getId();
                }

                //根据数组Ids查询所有商品属性名
                List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper
                        .queryPropertyNameByIds(ids);
                // 根据name去重
                List<ProductPropertyResponseFront> unique = productPropertyResponseFrontList.stream().collect(
                        Collectors.collectingAndThen(
                                Collectors.toCollection(
                                        () -> new TreeSet<>(Comparator.comparing(ProductPropertyResponseFront::getName))),
                                ArrayList::new)
                );
                if (productPropertyResponseFrontList.size() > 0) {
                    //重新封装属性名ids
                    Long[] productAttNameIds = new Long[productPropertyResponseFrontList.size()];
                    for (int i = 0; i < productAttNameIds.length; i++) {
                        productAttNameIds[i] = productPropertyResponseFrontList.get(i).getId();
                    }
                    //根据商品属性名ids查询所有商品属性值数据
                    List<ProductPropertyValueResponse> ppv = productMapper
                            .queryPropertyValueByIds(productAttNameIds);

                    //根据去重数据来组装前台需要展示的数据
                    for (ProductPropertyResponseFront productPropertyResponseFront : unique) {
                        List<ProductPropertyValueResponse> productPropertyValueResponseList = new ArrayList<>();
                        for (ProductPropertyValueResponse productPropertyValueResponse : ppv) {
                            if (productPropertyResponseFront.getAttNameId() == productPropertyValueResponse
                                    .getPropertyId()) {
                                productPropertyValueResponseList.add(productPropertyValueResponse);
                            }
                        }
                        productPropertyResponseFront.setProductPropertyValue(productPropertyValueResponseList);
                        productPropertyResponseFront.setId(id);
                        productPropertyResponseFront.setChineseName(productResponseFront.getChineseName());
                        productPropertyResponseFront
                                .setSalePriceWithTax(productResponseFront.getSalePriceWithTax());
                        productPropertyResponseFront.setPictureUrl(productResponseFront.getPictureUrl());
                        productPropertyResponseFront.setAvailableStock(productResponseFront.getAvailableStock());
                        productPropertyResponseFront.setTypeOfProduct(product.getTypeOfProduct());
                        list.add(productPropertyResponseFront);
                    }
            }
            } else {
                //没有商品属性名直接返回商品基本信息
                ProductPropertyResponseFront productPropertyResponseFront = new ProductPropertyResponseFront();
                productPropertyResponseFront.setId(id);
                productPropertyResponseFront.setChineseName(productResponseFront.getChineseName());
                productPropertyResponseFront
                        .setSalePriceWithTax(productResponseFront.getSalePriceWithTax());
                productPropertyResponseFront.setPictureUrl(productResponseFront.getPictureUrl());
                productPropertyResponseFront.setTypeOfProduct(product.getTypeOfProduct());
                list.add(productPropertyResponseFront);
            }
        } else {
            List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper
                    .queryPropertyNameById(product.getId());
            if (productPropertyResponseFrontList.size() > 0) {
                //重新封装属性名ids
                Long[] productAttNameIds = new Long[productPropertyResponseFrontList.size()];
                for (int i = 0; i < productAttNameIds.length; i++) {
                    productAttNameIds[i] = productPropertyResponseFrontList.get(i).getId();
                }
                //根据商品属性名ids查询所有商品属性值数据
                List<ProductPropertyValueResponse> ppv = productMapper.queryPropertyValueByIds(productAttNameIds);

                //单品查询所有属性值和名称
                for (ProductPropertyResponseFront productPropertyResponseFront : productPropertyResponseFrontList) {
                    List<ProductPropertyValueResponse> productPropertyValueResponseList = new ArrayList<>();
                    for (ProductPropertyValueResponse productPropertyValueResponse : ppv) {
                        if (productPropertyResponseFront.getAttNameId() == productPropertyValueResponse.getPropertyId()) {
                            productPropertyValueResponseList.add(productPropertyValueResponse);
                        }
                    }
                    productPropertyResponseFront.setId(productPropertyResponseFront.getProductId());
                    productPropertyResponseFront.setProductPropertyValue(productPropertyValueResponseList);
                    productPropertyResponseFront.setChineseName(productResponseFront.getChineseName());
                    productPropertyResponseFront.setSalePriceWithTax(productResponseFront.getSalePriceWithTax());
                    productPropertyResponseFront.setPictureUrl(productResponseFront.getPictureUrl());
                    productPropertyResponseFront.setAvailableStock(productResponseFront.getAvailableStock());
                    productPropertyResponseFront.setTypeOfProduct(productResponseFront.getTypeOfProduct());
                    productPropertyResponseFront.setMarketPrice(productPropertyResponseFront.getSalePriceWithTax().toString());
                    list.add(productPropertyResponseFront);
                }
            } else {
                //普通商品没有商品属性名直接返回商品基本信息
                ProductPropertyResponseFront productPropertyResponseFront = new ProductPropertyResponseFront();
                productPropertyResponseFront.setChineseName(productResponseFront.getChineseName());
                productPropertyResponseFront.setSalePriceWithTax(productResponseFront.getSalePriceWithTax());
                productPropertyResponseFront.setPictureUrl(productResponseFront.getPictureUrl());
                productPropertyResponseFront.setAvailableStock(productResponseFront.getAvailableStock());
                productPropertyResponseFront.setTypeOfProduct(productResponseFront.getTypeOfProduct());
                productPropertyResponseFront.setId(product.getId());
                productPropertyResponseFront.setMarketPrice(productResponseFront.getSalePriceWithTax().toString());
                list.add(productPropertyResponseFront);
            }

        }
        return list;
    }

    //h5查询商品基本信息
    @Override
    public ProductInfoResponse queryByProductId(long id) {
        return productMapper.queryByProductId(id);
    }

    //查询后台商品信息
    @Override
    public ProductAfterInfoResponse queryByAfterProductId(long id) {
        return productMapper.queryByAfterProductId(id);
    }

    @Override
    public long insert(Product product) {
        return productMapper.insert(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult saveProductDistribute(ProductDistributeRequest productDistributeRequest) {
        //查询商品信息
        Product product = this.queryByPrimaryKey(productDistributeRequest.getProductId());
        if (product != null) {
            //调用批量分发方法
            this.batchMerchant(product, productDistributeRequest.getMerchantRequestList());
        }
        return RestResult.success(product);
    }

    /**
     * 平台分发商品给商家或店铺
     *
     * @param product
     * @param deptId
     */
    @Transactional(rollbackFor = Exception.class)
    public Product saveMerchantOrStoreId(Product product, Long deptId, Long productId) {

        //添加商品基本信息
        product.setCode(IDUtils.GenerateBillNo("P"));
        Product product1 = this.saveProductInfo(product, deptId);

        //添加商品价格
        this.saveProductPrice(productId, deptId, product1.getId());

        //添加保障关联表
        this.saveProductGuaranteeRelation(productId, deptId, product1.getId());

        //添加商品文描 h5 pc
        this.saveProductDescribe(productId, deptId, product1.getId());

        //添加商品售后表
        this.saveProductAfterSale(productId, deptId, product1.getId());

        //添加商品属性名
        this.saveProductPropertyNameRelation(productId, deptId, product1.getId());

        //添加商品销售区域关联表
        this.saveProductSaleAreaRelation(productId, deptId, product1.getId());

        //添加商品图片
        this.saveProductMedia(productId, deptId, product1.getId());

        //添加组合商品
        this.saveProductBom(productId, deptId, product1.getId());

        //添加校标商品
        this.saveProductCalibration(productId, deptId, product1.getId());

        //默认插入品牌
        BrandManagementRequest brandManagementRequest = new BrandManagementRequest();
        brandManagementRequest.setBrandId(product1.getBrandId());
        brandManagementRequest.setStatus(2);
        brandManagementRequest.setDeptId(deptId);
        brandManagementRequest.setCreateTime(new Date());
        brandManagementMapper.insert(brandManagementRequest);

        return product1;
    }

    /**
     * 保存商品基本信息
     *
     * @param product
     * @param deptId
     */
    private Product saveProductInfo(Product product, Long deptId) {
        product.setDeptId(deptId);
        productMapper.insert(product);
        return product;
    }

    /**
     * 添加商品价格
     *
     * @param productId
     */
    private void saveProductPrice(Long productId, Long deptId, Long product1) {
        //查询商品价格
        ProductPrice productPrice = new ProductPrice();
        productPrice.setProductId(productId);
        productPrice = productPriceService.getProductPrice(productPrice);
        if (productPrice != null) {
            productPrice.setDeptId(deptId);
            productPrice.setProductId(product1);
            productPriceService.insert(productPrice);
        }
    }

    /**
     * 添加商品保障
     *
     * @param productId
     * @param deptId
     */
    private void saveProductGuaranteeRelation(Long productId, Long deptId, Long product1) {
        ProductGuaranteeRelation productGuaranteeRelation = new ProductGuaranteeRelation();
        productGuaranteeRelation.setProductId(productId);
        List<ProductGuaranteeRelation> productGuaranteeRelationList = productGuaranteeRelationService
                .query(productGuaranteeRelation);
        //保存商品保障关联
        for (ProductGuaranteeRelation productGuaranteeRelation1 : productGuaranteeRelationList) {
            productGuaranteeRelation1.setDeptId(deptId);
            productGuaranteeRelation1.setProductId(product1);
            productGuaranteeRelationMapper.insert(productGuaranteeRelation1);
        }
    }

    /**
     * 添加商品商品文描 h5 pc
     *
     * @param productId
     * @param deptId
     */
    private void saveProductDescribe(Long productId, Long deptId, Long product1) {
        ProductDescribe productDescribe = new ProductDescribe();
        productDescribe.setProductId(productId);
        List<ProductDescribe> productDescribeList = productDescribeService
                .getProductDescribe(productDescribe);
        for (ProductDescribe productDescribe1 : productDescribeList) {
            productDescribe1.setDeptId(deptId);
            productDescribe1.setProductId(product1);
            productDescribeService.insert(productDescribe1);
        }
    }

    /**
     * 添加商品售后表
     *
     * @param productId
     * @param deptId,
     */
    private void saveProductAfterSale(Long productId, Long deptId, Long product1) {
        //查询商品售后表
        ProductAfterSale productAfterSale = new ProductAfterSale();
        productAfterSale.setId(productId);
        productAfterSale = productAfterSaleService.getProductAfterSale(productAfterSale);
        if (productAfterSale != null) {
            productAfterSale.setProductId(product1);
            productAfterSale.setDeptId(deptId);
            productAfterSaleService.insert(productAfterSale);
        }
    }

    /**
     * 添加商品属性名
     *
     * @param productId
     * @param deptId
     */
    private void saveProductPropertyNameRelation(Long productId, Long deptId, Long product1) {
        ProductPropertyNameRelation productPropertyNameRelation = new ProductPropertyNameRelation();
        productPropertyNameRelation.setProductId(productId);
        List<ProductPropertyNameRelation> productPropertyNameRelations = productPropertyNameRelationService
                .query(productPropertyNameRelation);
        for (ProductPropertyNameRelation productPropertyNameRelation1 : productPropertyNameRelations) {
            Long productAttNameId = productPropertyNameRelation1.getId();
            productPropertyNameRelation1.setDeptId(deptId);
            productPropertyNameRelation1.setProductId(product1);
            productPropertyNameRelationService.insert(productPropertyNameRelation1);
            //查询商品属性值
            ProductPropertyValueRelation productPropertyValueRelation = new ProductPropertyValueRelation();
            productPropertyValueRelation.setProductAttNameId(productAttNameId);
            List<ProductPropertyValueRelation> productPropertyValueRelations = productPropertyValueRelationService
                    .query(productPropertyValueRelation);
            for (ProductPropertyValueRelation productPropertyValueRelation1 : productPropertyValueRelations) {
                productPropertyValueRelation1.setDeptId(deptId);
                productPropertyValueRelation1.setProductAttNameId(productPropertyNameRelation1.getId());
                productPropertyValueRelationService.insert(productPropertyValueRelation1);
            }
        }
    }

    /**
     * 添加商品销售区域关联表
     *
     * @param productId
     * @param deptId
     */
    private void saveProductSaleAreaRelation(Long productId, Long deptId, Long product1) {
        ProductSaleAreaRelation productSaleAreaRelation = new ProductSaleAreaRelation();
        productSaleAreaRelation.setProductId(productId);
        List<ProductSaleAreaRelation> productSaleAreaRelations = productSaleAreaRelationService
                .query(productSaleAreaRelation);
        for (ProductSaleAreaRelation productSaleAreaRelation1 : productSaleAreaRelations) {
            productSaleAreaRelation1.setDeptId(deptId);
            productSaleAreaRelation1.setProductId(product1);
            productSaleAreaRelationService.insert(productSaleAreaRelation1);
        }
    }

    /**
     * 添加商品图片
     *
     * @param productId
     * @param deptId
     */
    private void saveProductMedia(Long productId, Long deptId, Long product1) {
        ProductMedia productMedia = new ProductMedia();
        productMedia.setProductId(productId);
        List<ProductMedia> productMediaList = productMediaService.query(productMedia);
        for (ProductMedia productMedia1 : productMediaList) {
            productMedia1.setDeptId(deptId);
            productMedia1.setProductId(product1);
            productMediaService.insert(productMedia1);
        }
    }

    /**
     * 添加商品bom表
     *
     * @param productId
     * @param deptId
     */
    private void saveProductBom(Long productId, Long deptId, Long product1) {
        ProductBom productBom = new ProductBom();
        productBom.setProductParentId(productId);
        List<ProductBomResponse> productBomResponses = productBomMapper.query(productBom);
        for (ProductBomResponse productBomResponse : productBomResponses) {
            ProductBom productBom1 = new ProductBom();
            BeanUtils.copyProperties(productBomResponse, productBom1);
            productBom1.setDeptId(deptId);
            productBom1.setProductParentId(product1);
            productBomMapper.insert(productBom1);
        }
    }

    /**
     * 添加商品校标表
     *
     * @param productId
     * @param deptId
     */
    private void saveProductCalibration(Long productId, Long deptId, Long product1) {
        ProductCalibration productCalibration = new ProductCalibration();
        productCalibration.setProductParentId(productId);
        List<ProductCalibrationResponse> productCalibrationResponseList = productCalibrationMapper.query(productCalibration);
        for (ProductCalibrationResponse productCalibrationResponse : productCalibrationResponseList) {
            ProductCalibration productCalibration1 = new ProductCalibration();
            BeanUtils.copyProperties(productCalibrationResponse, productCalibration1);
            productCalibration1.setDeptId(deptId);
            productCalibration1.setProductParentId(product1);
            productCalibrationMapper.insert(productCalibration1);
        }
    }

    /**
     * 添加店铺类目
     *
     * @param categoryId
     * @param deptId
     */
    private void saveCategoryMerchantRelation(Long categoryId, Long deptId) {
        CategoryMerchantRelation categoryMerchantRelation = new CategoryMerchantRelation();
        categoryMerchantRelation.setCategoryId(categoryId);
        categoryMerchantRelation.setDeptId(deptId);
        categoryMerchantRelation.setIsDisplay(1);
        categoryMerchantRelation.setType(2);
        List<CategoryMerchantRelation> list = categoryMerchantRelationService.query(categoryMerchantRelation);
        if (list.isEmpty()) {
            categoryMerchantRelation.setCreateTime(new Date());
            categoryMerchantRelationService.insert(categoryMerchantRelation);
        }
    }

    //查询后台商品图片和价格
    @Override
    public ProductAfterInfoByIdResponse queryProductInfoById(long id) {
        return productMapper.queryProductInfoById(id);
    }

    @Override
    public ProductAfterInfoByIdResponse queryProductInfoBythirdProductCode(String thirdProductCode) {
        return productMapper.queryProductInfoBythirdProductCode(thirdProductCode);
    }


    //查询商品商家和店铺信息
    @Override
    public ShoppingCartResponse queryBusinessInfoByProductId(long id) {
        ShoppingCartResponse shoppingCartResponse = productMapper.queryBusinessInfoByProductId(id);
        if (shoppingCartResponse != null) {
            //根据数组Ids查询所有商品属性名
            List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper
                    .queryPropertyNameById(id);
            List<ProductPropertyResponse> productPropertyResponseList = new ArrayList<>();
            for (ProductPropertyResponseFront productPropertyResponseFront : productPropertyResponseFrontList) {
                ProductPropertyResponse productPropertyResponse = new ProductPropertyResponse();
                productPropertyResponse.setAttrName(productPropertyResponseFront.getName());
                productPropertyResponse.setAttrId(productPropertyResponseFront.getAttNameId());
                //根据商品属性名ids查询所有商品属性值数据
                List<ProductPropertyValueResponse> ppv = productMapper
                        .queryPropertyValueById(productPropertyResponseFront.getId());
                if (CollectionUtils.isNotEmpty(ppv)) {
                    productPropertyResponse.setValueName(ppv.get(0).getValueName());
                    productPropertyResponse.setValueId(ppv.get(0).getValueId());
                    productPropertyResponseList.add(productPropertyResponse);
                }
            }
            shoppingCartResponse.setProductPropertyValue(productPropertyResponseList);
        }
        return shoppingCartResponse;
    }

    /**
     * 前端--选择规格接口
     *
     * @param productId
     * @return
     */
    @Override
    public RestResult<List<ProductSkuResponse>> getSkuListByProdId(Long productId, String promotionId) {
        List<ProductSkuResponse> productSkuResponseList = new ArrayList<>();
        //查询商品
        Product product = productMapper.queryByPrimaryKey(productId);
        if (product == null) {
            return RestResult.error("9999", "商品不存在！");
        }
        if (product.getTypeOfProduct() == 3) {
            Product product1 = productMapper.queryByPrimaryKey(product.getParentId());
            BeanUtils.copyProperties(product1, product);
        }
        //判断是普通商品还是系列品
        if (product.getTypeOfProduct() == 2) {
            //根据系列虚品的Id 查询所有子商品
            product.setParentId(product.getId());
            List<Product> products = productMapper.query(product);

            // 查询商品是否参与单一促销
            List<Long> mpIds = products.stream().map(temp->{
                return temp.getId();
            }).collect(Collectors.toList());
            RestResult<List<PromotionSingleProductResponse>> singleProductResponseRestResult = marketApi.querySingleByMpIds(mpIds);
            List<PromotionSingleProductResponse> singleProductList= singleProductResponseRestResult.getData();
            for (Product product1 : products) {
                //查询商品基本信息
                ProductResponseFront productResponseFront = productMapper.getProductInfoById(product1.getId());
                //封装返回数据
                ProductSkuResponse productSkuResponse = new ProductSkuResponse();
                //拼团信息
                if (StringUtils.isNotEmpty(promotionId)) {
                    GrouponInfoRequest request = new GrouponInfoRequest();
                    request.setThirdProductCode(product1.getCode());
                    request.setGroupCode(promotionId);
                    request.setProductType(20);
                    RestResult<GrouponInfoResponse> responseRestResult = marketApi.getGroupInfo(request);
                    GrouponInfoResponse groupInfoFeignResponse = responseRestResult.getData();
                    if (groupInfoFeignResponse != null) {
                        //营销价
                        productResponseFront.setMarketPrice(groupInfoFeignResponse.getAvailablePrice());

                    }
                } else {
                    productResponseFront.setMarketPrice(productResponseFront.getSalePriceWithTax());
                }

                if (singleProductList != null && singleProductList.size()!=0){
                    PromotionSingleProductResponse singleProduct = singleProductList.stream().filter(temp->
                       temp.getMpId().toString().equals(product1.getId().toString())
                    ).findAny().orElse(null);
                    if(null != singleProduct){
                        if (singleProduct.getFrontPromType().toString().equals("1")) {
                            productResponseFront.setMarketPrice(singleProduct.getContentValue());
                        } else if (singleProduct.getFrontPromType().toString().equals("2")) {
                            BigDecimal discount = singleProduct.getContentValue().divide(new BigDecimal("10"));
                            productResponseFront.setMarketPrice(productResponseFront.getSalePriceWithTax().multiply(discount));
                        } else if (singleProduct.getFrontPromType().toString().equals("3")) {
                            productResponseFront.setMarketPrice(productResponseFront.getSalePriceWithTax().subtract(singleProduct.getContentValue()));
                        }
                    }

                }
                BeanUtils.copyProperties(productResponseFront, productSkuResponse);
                //根据数组Ids查询所有商品属性名
                List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper.queryPropertyNameById(product1.getId());
                List<ProductPropertyResponse> productPropertyResponseList = new ArrayList<>();
                for (ProductPropertyResponseFront productPropertyResponseFront : productPropertyResponseFrontList) {
                    ProductPropertyResponse productPropertyResponse = new ProductPropertyResponse();
                    productPropertyResponse.setAttrId(productPropertyResponseFront.getAttNameId());
                    productPropertyResponse.setAttrName(productPropertyResponseFront.getName());
                    //根据商品属性名ids查询所有商品属性值数据
                    List<ProductPropertyValueResponse> ppv = productMapper.queryPropertyValueById(productPropertyResponseFront.getId());
                    if (CollectionUtils.isNotEmpty(ppv)) {
                        productPropertyResponse.setValueId(ppv.get(0).getValueId());
                        productPropertyResponse.setValueName(ppv.get(0).getValueName());
                        productPropertyResponseList.add(productPropertyResponse);
                    }
                }
                productSkuResponse.setProductPropertyValue(productPropertyResponseList);
                productSkuResponseList.add(productSkuResponse);
            }

        } else {
            //查询商品基本信息
            ProductResponseFront productResponseFront = productMapper.getProductInfoById(product.getId());
            //封装返回数据
            ProductSkuResponse productSkuResponse = new ProductSkuResponse();
            //营销价
            //拼团信息
            if (StringUtils.isNotEmpty(promotionId)) {
                GrouponInfoRequest request = new GrouponInfoRequest();
                request.setGroupCode(promotionId);
                request.setThirdProductCode(productResponseFront.getCode());
                request.setProductType(20);
                RestResult<GrouponInfoResponse> responseRestResult = marketApi.getGroupInfo(request);
                GrouponInfoResponse groupInfoFeignResponse = responseRestResult.getData();
                if (groupInfoFeignResponse != null) {
                    //营销价
                    productResponseFront.setMarketPrice(groupInfoFeignResponse.getAvailablePrice());

                }
            } else {
                productResponseFront.setMarketPrice(productResponseFront.getSalePriceWithTax());
            }
            productResponseFront.setTypeOfProduct(productResponseFront.getTypeOfProduct());
            BeanUtils.copyProperties(productResponseFront, productSkuResponse);
            //根据数组Ids查询所有商品属性名
            List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper.queryPropertyNameById(product.getId());
            List<ProductPropertyResponse> productPropertyResponseList = new ArrayList<>();
            for (ProductPropertyResponseFront productPropertyResponseFront : productPropertyResponseFrontList) {
                ProductPropertyResponse productPropertyResponse = new ProductPropertyResponse();
                productPropertyResponse.setAttrName(productPropertyResponseFront.getName());
                productPropertyResponse.setAttrId(productPropertyResponseFront.getAttNameId());
                //根据商品属性名ids查询所有商品属性值数据
                List<ProductPropertyValueResponse> ppv = productMapper.queryPropertyValueById(productPropertyResponseFront.getId());
                productPropertyResponse.setValueId(ppv.get(0).getValueId());
                productPropertyResponse.setValueName(ppv.get(0).getValueName());
                productPropertyResponseList.add(productPropertyResponse);
            }
            productSkuResponse.setProductPropertyValue(productPropertyResponseList);
            productSkuResponseList.add(productSkuResponse);
        }
        return RestResult.success(productSkuResponseList);
    }

    @Override
    public RestResult<Boolean> saveMerchantProduct(SaveProductRequest productInfoRequest) {
        List<Product> productList = productMapper.queryProductDeptIdList(productInfoRequest);
        for (Product product : productList) {
            this.saveMerchantOrStoreId(product, productInfoRequest.getDeptId(), null);
        }
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> saveStoreProduct(SaveProductRequest productInfoRequest) {
        List<Product> productList = productMapper.queryProductMerchantIdList(productInfoRequest);
        for (Product product : productList) {
            this.saveMerchantOrStoreId(product, productInfoRequest.getDeptId(), product.getId());
        }
        return RestResult.success(true);
    }

    @Override
    public RestResult<List<ProductParentResponse>> getProductParent(
            GetProductParentRequest getProductParentRequest) {
        //查询商品信息是否是系列品
        Product product = this.queryByPrimaryKey(getProductParentRequest.getProductId());
        Product product1 = new Product();
        if (product != null) {
            if (product.getTypeOfProduct() == 1) {
                product1.setId(product.getId());
            } else {
                //根据系列虚品的Id 查询所有子商品
                product1.setParentId(product.getId());
            }
        } else {
            return RestResult.error("9999", "商品记录不存在");
        }
        List<ProductParentResponse> productParentResponseList = productMapper
                .getProductListByParentId(product1);
        for (ProductParentResponse productParentResponse : productParentResponseList) {
            productParentResponse.setFreightTemplateId(product.getFreightTemplateId());
            List<ProductPropertyManageResponse> productPropertyResponseList = new ArrayList<>();
            //根据数组Ids查询所有商品属性名
            List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper
                    .queryPropertyNameById(productParentResponse.getId());
            for (ProductPropertyResponseFront productPropertyResponseFront : productPropertyResponseFrontList) {
                //查询属性值
                List<ProductPropertyValueResponse> productPropertyValueResponseList = productMapper
                        .queryPropertyValueById(productPropertyResponseFront.getId());
                //封装返回对象
                ProductPropertyManageResponse productPropertyResponse = new ProductPropertyManageResponse();
                productPropertyResponse.setAttrId(productPropertyResponseFront.getId());
                productPropertyResponse.setAttrName(productPropertyResponseFront.getName());
                productPropertyResponse.setValueId(productPropertyValueResponseList.get(0).getValueId());
                productPropertyResponse
                        .setValueName(productPropertyValueResponseList.get(0).getValueName());
                productPropertyResponseList.add(productPropertyResponse);
                productParentResponse.setProductPropertyResponseList(productPropertyResponseList);
            }
        }
        return RestResult.success(productParentResponseList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult saveProductDistributeStore(ProductDistributeStoreRequest productDistributeStoreRequest) {
        //查询商品信息是否是系列品
        Product product = this.queryByPrimaryKey(productDistributeStoreRequest.getProductId());
        product.setFreightTemplateId(productDistributeStoreRequest.getFreightTemplateId());
        if (product != null) {
            // 分发记录表
            ProductDistribute productDistribute = new ProductDistribute();
            BeanUtils.copyProperties(productDistributeStoreRequest, productDistribute);
            long count = productDistributeMapper.queryDistributeCount(productDistribute);
            if (count > 0) {
                return RestResult.error("9999", "该商品店铺已存在");
            }
            productDistributeService.insert(productDistribute);
            // 初始商品ID
            Long productId = product.getId();
            // 1-普通商品;2-系列子品
            Integer typeOfProduct = product.getTypeOfProduct();
            // 商品来源类型:1-平台;2-商家
            product.setSourceType(2);
            // 商品数据类型:1-运营商品;2-商家商品;3-店铺商品;
//            product.setDataType(3);
            // 商品资料引用ID, 如果是门店商品 ref_id =商家商品ID（）
            product.setRefId(product.getId());
            // 分发时商品默认上架
            product.setCanSale(1);
            // 店铺名称
            product.setStoreName(productDistributeStoreRequest.getStoreName());
            // 在商品分发给店铺时插入渠道名称
            product.setChannelName(productDistributeStoreRequest.getChannelName());
            if (typeOfProduct == 1) {
                this.saveStore(product, productDistributeStoreRequest.getDeptId(), productId);
            } else {
                this.saveMerchantOrStoreId(product, productDistributeStoreRequest.getDeptId(), productId);
            }
            for (ProductDistributeStoreParentRequest productDistributeStoreParentRequest : productDistributeStoreRequest
                    .getProductDistributeStoreParentRequests()) {
                if (typeOfProduct == 2) {
                    // 查询商品信息是否是系列品
                    Product product2 = this
                            .queryByPrimaryKey(productDistributeStoreParentRequest.getProductId());
                    product2.setParentId(product.getId());
                    // 商品来源类型:1-平台;2-商家
                    product2.setSourceType(2);
                    // 商品数据类型:1-运营商品;2-商家商品;3-店铺商品;
//                    product2.setDataType(3);
                    // 上架
                    product2.setCanSale(1);
                    product2.setStoreName(productDistributeStoreRequest.getStoreName());
                    // 在商品分发给店铺时插入渠道名称
                    product2.setChannelName(productDistributeStoreRequest.getChannelName());
                    this.saveStore(product2, productDistributeStoreRequest.getDeptId(),
                            productDistributeStoreParentRequest.getProductId());
                    //插入子品价格
                    ProductPrice productPrice = new ProductPrice();
                    productPrice.setProductId(product2.getId());
                    productPrice.setMarketPrice(productDistributeStoreParentRequest.getMarketPrice());
                    productPrice
                            .setSalePriceWithTax(productDistributeStoreParentRequest.getSalePriceWithTax());
                    productPrice
                            .setGroupBuyingPrice(productDistributeStoreParentRequest.getGroupBuyingPrice());
                    productPrice.setPurchasePriceWithTax(
                            productDistributeStoreParentRequest.getPurchasePriceWithTax());
//                    productPrice.setDataType(3);
                    productPrice.setStoreId(productDistributeStoreRequest.getStoreId());
                    productPrice.setStoreName(productDistributeStoreRequest.getStoreName());
                    productPrice.setCreator(productDistributeStoreRequest.getCreator());
                    productPriceService.insert(productPrice);

                    //保存店铺库存
                    StoreInventory storeInventory = new StoreInventory();
                    storeInventory.setTotalStock(productDistributeStoreParentRequest.getAvailableStock());
                    storeInventory.setAvailableStock(productDistributeStoreParentRequest.getAvailableStock());
                    storeInventory.setProductId(product2.getId());
                    storeInventory.setDeptName(product2.getDeptName());
                    storeInventory.setStoreId(product2.getStoreId());
                    storeInventory.setStoreName(product2.getStoreName());
                    storeInventory.setDeptId(product2.getDeptId());
                    storeInventory.setCreator(productDistributeStoreRequest.getCreator());
                    storeInventoryMapper.insert(storeInventory);
                } else {
                    //插入子品价格
                    ProductPrice productPrice = new ProductPrice();
                    productPrice.setProductId(product.getId());
                    productPrice.setMarketPrice(productDistributeStoreParentRequest.getMarketPrice());
                    productPrice.setSalePriceWithTax(productDistributeStoreParentRequest.getSalePriceWithTax());
                    productPrice.setGroupBuyingPrice(productDistributeStoreParentRequest.getGroupBuyingPrice());
                    productPrice.setPurchasePriceWithTax(productDistributeStoreParentRequest.getPurchasePriceWithTax());
//                    productPrice.setDataType(3);
                    productPrice.setStoreName(productDistributeStoreRequest.getStoreName());
                    productPrice.setCreator(productDistributeStoreRequest.getCreator());
                    productPriceService.insert(productPrice);

                    //保存店铺库存
                    StoreInventory storeInventory = new StoreInventory();
                    storeInventory.setTotalStock(productDistributeStoreParentRequest.getAvailableStock());
                    storeInventory.setAvailableStock(productDistributeStoreParentRequest.getAvailableStock());
                    storeInventory.setProductId(product.getId());
                    storeInventory.setDeptName(product.getDeptName());
                    storeInventory.setStoreId(product.getStoreId());
                    storeInventory.setStoreName(product.getStoreName());
                    storeInventory.setDeptId(product.getDeptId());
                    storeInventory.setCreator(productDistributeStoreRequest.getCreator());
                    storeInventoryMapper.insert(storeInventory);
                }
            }
        }
        return RestResult.success(product);
    }

    @Override
    public RestResult<Boolean> saveProductParent(ProductParentRequest productParentRequest) {
        //查询商品信息
        Product product = this.queryByPrimaryKey(productParentRequest.getProductId());
        for (ProductPropertyRequest productPropertyRequest : productParentRequest.getProductPropertyRequest()) {
            product.setParentId(productParentRequest.getProductId());
            product.setTypeOfProduct(3);
            product.setBarCode(null);
            product.setThirdProductCode(null);
            productMapper.insert(product);

            //添加商品价格
            ProductPrice productPrice = new ProductPrice();
            productPrice.setProductId(product.getId());
//            productPrice.setDataType(productParentRequest.getDataType());
            productPriceService.insert(productPrice);
            //添加商品图片
            ProductMedia productMedia = new ProductMedia();
            productMedia.setProductId(product.getId());
            productMedia.setType(1);
            productMedia.setIsMainPicture(1);
            productMediaMapper.insert(productMedia);
            for (ProductPropertyRequest productPropertyRequest1 : productPropertyRequest.getAttList()) {
                //商品属性名
                ProductPropertyNameRelation productPropertyNameRelation = new ProductPropertyNameRelation();
                productPropertyNameRelation.setProductId(product.getId());
                productPropertyNameRelation.setAttNameId(productPropertyRequest1.getAttrId());
                productPropertyNameRelationService.insert(productPropertyNameRelation);

                //查询商品属性值
                ProductPropertyValueRelation productPropertyValueRelation = new ProductPropertyValueRelation();
                productPropertyValueRelation.setProductAttNameId(productPropertyNameRelation.getId());
                productPropertyValueRelation.setAttValueId(productPropertyRequest1.getValueId());
                productPropertyValueRelationService.insert(productPropertyValueRelation);
            }
        }
        return RestResult.success(true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<Boolean> updateProductParentPrice(
            ProductParentPriceRequest productParentPriceRequest) {
        for (ProductDistributeStoreParentRequest productDistributeStoreParentRequest : productParentPriceRequest
                .getProductDistributeStoreParentRequestList()) {
            //更新子品价格
            ProductPrice productPrice = new ProductPrice();
            productPrice.setProductId(productDistributeStoreParentRequest.getProductId());
            productPrice.setMarketPrice(productDistributeStoreParentRequest.getMarketPrice());
            productPrice.setSalePriceWithTax(productDistributeStoreParentRequest.getSalePriceWithTax());
            productPrice.setGroupBuyingPrice(productDistributeStoreParentRequest.getGroupBuyingPrice());
            productPrice.setPurchasePriceWithTax(productDistributeStoreParentRequest.getPurchasePriceWithTax());
            productPriceService.update(productPrice);

            //更新商品基本信息
            Product product = new Product();
            product.setId(productDistributeStoreParentRequest.getProductId());
            product.setBarCode(productDistributeStoreParentRequest.getBarCode());
            product.setThirdProductCode(productDistributeStoreParentRequest.getThirdProductCode());
            productMapper.update(product);

            //更新商品图片
            ProductMedia productMedia = new ProductMedia();
            productMedia.setProductId(productDistributeStoreParentRequest.getProductId());
            productMedia.setPictureUrl(productDistributeStoreParentRequest.getPictureUrl());
            productMediaMapper.updateByProductId(productMedia);

            //更新库存信息
            StoreInventory storeInventory = new StoreInventory();
            storeInventory.setProductId(productDistributeStoreParentRequest.getProductId());
            storeInventory.setTotalStock(productDistributeStoreParentRequest.getTotalStock());
            storeInventory.setAvailableStock(productDistributeStoreParentRequest.getAvailableStock());
            storeInventoryMapper.updateByProductId(storeInventory);

        }
        return RestResult.success(true);
    }

    @Override
    public RestResult deleteProductParent(Long productId) {
        return RestResult.success(productMapper.deleteProductParent(productId));
    }

    @Override
    public RestResult<Boolean> updateProductDistributeStore(
            ProductDistributeStoreRequest productDistributeStoreRequest) {
        for (ProductDistributeStoreParentRequest productDistributeStoreParentRequest : productDistributeStoreRequest
                .getProductDistributeStoreParentRequests()) {
            // 更新库存
            if (productDistributeStoreParentRequest.getAvailableStock() != null) {
                //查询店铺库存信息
                StoreInventory storeInventory = storeInventoryMapper
                        .queryByProductId(productDistributeStoreParentRequest.getProductId());
                if (storeInventory != null) {
                    //更新库存-冻结库存=可售库存
                    Integer availableStock =
                            productDistributeStoreParentRequest.getAvailableStock() - storeInventory.getBlockStock();
                    if (availableStock < 0) {
                        return RestResult.error("9999", "库存不能小于冻结库存");
                    }
                    storeInventory.setAvailableStock(availableStock);
                    storeInventory.setTotalStock(productDistributeStoreParentRequest.getAvailableStock());
                    storeInventory.setDayStock(productDistributeStoreParentRequest.getDayStock());
                    storeInventory.setUpdateTime(new Date());
                    //修改库存信息
                    storeInventoryMapper.update(storeInventory);
                }
            }
            // 更新子品价格
            ProductPrice productPrice = new ProductPrice();
            productPrice.setProductId(productDistributeStoreParentRequest.getProductId());
            productPrice.setMarketPrice(productDistributeStoreParentRequest.getMarketPrice());
            // 是否有审核记录 0否 其它有
            if (productDistributeStoreParentRequest.getIsAudit() == 0) {
                //查询改动前的值
                ProductPrice productPrice1 = productPriceMapper.getProductPrice(productPrice);
                if (null == productPrice1) {
                    ProductPriceAudit productPriceAudit = new ProductPriceAudit();
                    productPriceAudit.setBeforeValue(null);
                    productPriceAudit.setAfterValue(productDistributeStoreParentRequest.getSalePriceWithTax());
                    productPriceAudit.setProductId(productDistributeStoreParentRequest.getProductId());
                    productPriceAudit.setStatus(0L);
//                    productPriceAudit.setDataType(3);
                    productPriceAudit.setCreateTime(new Date());
                    productPriceAuditMapper.insertProductPriceAudit(productPriceAudit);
                } else {
                    //金额相同不做审核处理
                    BigDecimal salePriceWithTax =
                            productPrice1.getSalePriceWithTax() == null ? BigDecimal.ZERO : productPrice1.getSalePriceWithTax();
                    BigDecimal salePriceWithTax1 =
                            productDistributeStoreParentRequest.getSalePriceWithTax() == null ? BigDecimal.ZERO : productDistributeStoreParentRequest.getSalePriceWithTax();
                    if (salePriceWithTax.compareTo(salePriceWithTax1) != 0) {
                        ProductPriceAudit productPriceAudit = new ProductPriceAudit();
                        productPriceAudit.setBeforeValue(productPrice1.getSalePriceWithTax());
                        productPriceAudit.setAfterValue(productDistributeStoreParentRequest.getSalePriceWithTax());
                        productPriceAudit.setProductId(productDistributeStoreParentRequest.getProductId());
                        productPriceAudit.setStatus(0L);
//                        productPriceAudit.setDataType(3);
                        productPriceAudit.setCreateTime(new Date());
                        productPriceAuditMapper.insertProductPriceAudit(productPriceAudit);
                    }
                }
            }
            productPrice.setGroupBuyingPrice(productDistributeStoreParentRequest.getGroupBuyingPrice());
            productPrice.setPurchasePriceWithTax(productDistributeStoreParentRequest.getPurchasePriceWithTax());
            productPrice.setUpdateTime(new Date());
            productPriceMapper.updateProductDistributeStore(productPrice);
            // 修改运费模板
            if (productDistributeStoreRequest.getFreightTemplateId() > 0) {
                Product product = new Product();
                product.setId(productDistributeStoreParentRequest.getProductId());
                product.setFreightTemplateId(productDistributeStoreRequest.getFreightTemplateId());
                productMapper.update(product);
            }
            // 修改上下架功能
            if (productDistributeStoreParentRequest.getCanSale() != null) {
                Product product = new Product();
                product.setId(productDistributeStoreParentRequest.getProductId());
                product.setCanSale(productDistributeStoreParentRequest.getCanSale());
                product.setUpdateTime(new Date());
                productMapper.update(product);
            }
            //修改第三方编码
            if (StringUtils.isNotEmpty(productDistributeStoreParentRequest.getThirdProductCode())) {
                Product product = new Product();
                product.setId(productDistributeStoreParentRequest.getProductId());
                product.setThirdProductCode(productDistributeStoreParentRequest.getThirdProductCode());
                productMapper.update(product);
            }
        }
        return RestResult.success(true);
    }

    @Override
    public ProductResponse queryProductInfo(Long id) {
        return productMapper.queryProductInfo(id);
    }

    @Override
    public void updateProductInfo(ProductInfoUpdateRequest productInfoUpdateRequest) {
        Product product = BeanUtil.copy(productInfoUpdateRequest, Product.class);
        product.setUpdateTime(new Date());
        productMapper.updateProductInfo(product);
    }

    @Override
    public RestResult<List<ProductAfterResponse>> queryProductListByProdId(List<Long> productIds) {
        List<ProductAfterResponse> productAfterResponseList = new ArrayList<>();
        for (Long productId : productIds) {
            List<ProductAfterSonResponse> productAfterSonResponseList = new ArrayList<>();
            //查询商品
            Product product = productMapper.queryByPrimaryKey(productId);
            if (product == null) {
                continue;
            }
            //判断是普通商品还是系列品
            if (product.getTypeOfProduct() == 2) {
                //主品数据
                ProductAfterResponse productAfterResponse = productMapper
                        .queryProductListByProdId(product.getId());
                //根据系列虚品的Id 查询所有子商品
                product.setParentId(product.getId());
                List<Product> products = productMapper.queryProductByParentId(product);
                for (Product product1 : products) {
                    //查询商品基本信息
                    ProductAfterResponse productAfterResponse1 = productMapper
                            .queryProductListByProdId(product1.getId());
                    //子品集合
                    ProductAfterSonResponse productAfterSonResponse = new ProductAfterSonResponse();
                    BeanUtils.copyProperties(productAfterResponse1, productAfterSonResponse);
                    productAfterSonResponse.setParentId(product.getId());
                    //根据数组Ids查询所有商品属性名
                    List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper
                            .queryPropertyNameById(product1.getId());
                    List<ProductPropertyResponse> productPropertyResponseList = new ArrayList<>();
                    for (ProductPropertyResponseFront productPropertyResponseFront : productPropertyResponseFrontList) {
                        ProductPropertyResponse productPropertyResponse = new ProductPropertyResponse();
                        productPropertyResponse.setAttrId(productPropertyResponseFront.getAttNameId());
                        productPropertyResponse.setAttrName(productPropertyResponseFront.getName());
                        //根据商品属性名ids查询所有商品属性值数据
                        List<ProductPropertyValueResponse> ppv = productMapper
                                .queryPropertyValueById(productPropertyResponseFront.getId());
                        if (CollectionUtils.isNotEmpty(ppv)) {
                            productPropertyResponse.setValueId(ppv.get(0).getValueId());
                            productPropertyResponse.setValueName(ppv.get(0).getValueName());
                            productPropertyResponseList.add(productPropertyResponse);
                        }
                    }
                    productAfterSonResponse.setProductPropertyValue(productPropertyResponseList);
                    productAfterSonResponseList.add(productAfterSonResponse);
                }
                productAfterResponse.setProductAfterSonResponse(productAfterSonResponseList);
                productAfterResponseList.add(productAfterResponse);

            } else {
                //子品集合
                ProductAfterSonResponse productAfterSonResponse = new ProductAfterSonResponse();
                //查询商品基本信息
                ProductAfterResponse productAfterResponse = productMapper
                        .queryProductListByProdId(product.getId());
                BeanUtils.copyProperties(productAfterResponse, productAfterSonResponse);
                //根据数组Ids查询所有商品属性名
                List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper
                        .queryPropertyNameById(product.getId());
                List<ProductPropertyResponse> productPropertyResponseList = new ArrayList<>();
                for (ProductPropertyResponseFront productPropertyResponseFront : productPropertyResponseFrontList) {
                    ProductPropertyResponse productPropertyResponse = new ProductPropertyResponse();
                    productPropertyResponse.setAttrName(productPropertyResponseFront.getName());
                    productPropertyResponse.setAttrId(productPropertyResponseFront.getAttNameId());
                    //根据商品属性名ids查询所有商品属性值数据
                    List<ProductPropertyValueResponse> ppv = productMapper
                            .queryPropertyValueById(productPropertyResponseFront.getId());
                    productPropertyResponse.setValueId(ppv.get(0).getValueId());
                    productPropertyResponse.setValueName(ppv.get(0).getValueName());
                    productPropertyResponseList.add(productPropertyResponse);
                }
                productAfterSonResponse.setProductPropertyValue(productPropertyResponseList);
                productAfterSonResponseList.add(productAfterSonResponse);
                productAfterResponse.setProductAfterSonResponse(productAfterSonResponseList);
                productAfterResponseList.add(productAfterResponse);
            }
        }

        return RestResult.success(productAfterResponseList);
    }

    /**
     * 查询店铺商品
     *
     * @param meStoreListRequestList
     * @return
     */
    @Override
    public RestResult<List<MeStoreListResponse>> queryMeStoreList(
            List<MeStoreListRequest> meStoreListRequestList) {
        //查询店铺商品
        List<MeStoreListResponse> meStoreListResponseList = new ArrayList<>();
        for (MeStoreListRequest meStoreListRequest : meStoreListRequestList) {

            long count = productMapper.queryProductByStoreId(meStoreListRequest.getDeptId());
            if (count > 0) {
                MeStoreListResponse meStoreListResponse = new MeStoreListResponse();
                BeanUtils.copyProperties(meStoreListRequest, meStoreListResponse);
                meStoreListResponseList.add(meStoreListResponse);
            }

        }
        return RestResult.success(meStoreListResponseList);
    }

    /**
     * 根据IDs查询商品
     *
     * @param productIds
     * @return
     */
    @Override
    public RestResult<List<ProductResponseFront>> queryProductListByIds(List<Long> productIds) {

        return RestResult.success(productMapper.queryProductListById(productIds));
    }

    @Override
    public RestResult<PageResult<GoodsSpuPageQueryResponse>> queryProductList(
            GoodsSpuPageQueryRequest request) {
        //计算下标
        int startIndex = (request.getStart() - 1) * request.getLimit();
        List<ShopInfoResponse> list = productMapper.queryShopPage(startIndex, request.getLimit(), new ShopInfoRequest() {{
            setChineseName(request.getGoodsName());
            setStoreIds(request.getStoreIds());
            setDeleteFlag(0);
            setTypeOfProduct(2);
            setProductCategoryName(request.getGoodsCategory());
        }});

        long total = productMapper.queryShopCount(new ShopInfoRequest() {{
            setChineseName(request.getGoodsName());
            setStoreIds(request.getStoreIds());
            setDeleteFlag(0);
            setTypeOfProduct(2);
            setProductCategoryName(request.getGoodsCategory());
        }});
        List<GoodsSpuPageQueryResponse> restList = new ArrayList<>();
        list.forEach(productResponse -> {
            GoodsSpuPageQueryResponse goodsSpuPageQueryResponse = new GoodsSpuPageQueryResponse();
            goodsSpuPageQueryResponse.setGoodsName(productResponse.getChineseName());
            Category category = categoryMapper.queryByPrimaryKey(Long.valueOf(productResponse.getCategoryId()));
            goodsSpuPageQueryResponse.setGoodsCategory(category == null ? null : category.getName());
            goodsSpuPageQueryResponse.setSalePriceScope(productResponse.getSalePriceWithTax() == null ? ""
                    : productResponse.getSalePriceWithTax().toString());
            goodsSpuPageQueryResponse.setStock(productResponse.getTotalStock());
            goodsSpuPageQueryResponse.setDeptId(productResponse.getDeptId());
            goodsSpuPageQueryResponse.setDeptName(productResponse.getDeptName());
            goodsSpuPageQueryResponse.setStoreId(productResponse.getStoreId());
            goodsSpuPageQueryResponse.setStoreName(productResponse.getStoreName());
            goodsSpuPageQueryResponse.setId(productResponse.getId());
            restList.add(goodsSpuPageQueryResponse);
        });

        return RestResult.success(new PageResult<GoodsSpuPageQueryResponse>() {{
            setRows(restList);
            setTotal(total);
        }});
    }

    /**
     * 根据条件查询spu列表
     *
     * @param request
     * @return
     */
    @Override
    public RestResult<PageResult<GoodsPageQueryResponse>> queryByAllCondition(
            GoodsPageQueryRequest request) {
        List<GoodsPageQueryResponse> goodsPageQueryResponses = new ArrayList<>();
        //计算下标
        int startIndex = (request.getStart() - 1) * request.getLimit();
        List<ShopInfoResponse> list = productMapper.queryShopPage(startIndex, request.getLimit(), new ShopInfoRequest() {{
            setChineseName(request.getGoodsName());
            setStoreIds(request.getStoreIds());
            setDeleteFlag(0);
            setTypeOfProduct(2);
            setProductCategoryName(request.getGoodsCategory());
        }});
        long total = productMapper.queryShopCount(new ShopInfoRequest() {{
            setChineseName(request.getGoodsName());
            setStoreIds(request.getStoreIds());
            setDeleteFlag(0);
            setTypeOfProduct(2);
            setProductCategoryName(request.getGoodsCategory());
        }});
        list.forEach(shopInfoResponse -> {
            goodsPageQueryResponses.add(this.packagedGoods(encapsulationProduct2(shopInfoResponse),
                    shopInfoResponse.getTypeOfProduct(), shopInfoResponse.getId()));
        });
        return RestResult.success(new PageResult<GoodsPageQueryResponse>() {{
            setRows(goodsPageQueryResponses);
            setTotal(total);
        }});
    }

    /**
     * 根据产品id查询产品信息
     *
     * @param productId
     * @return
     */
    @Override
    public RestResult<GoodsPageQueryResponse> queryMarketById(Long productId) {
        //查询商品基本信息
        ProductAfterResponse productAfterResponse = productMapper.queryProductListByProdId(productId);
        if (productAfterResponse == null) {
            return RestResult.error("9999", "商品不存在");
        }
        GoodsQueryInfo goodsQueryInfo = encapsulationProduct1(productAfterResponse);
        GoodsPageQueryResponse goodsPageQueryResponse = this.packagedGoods(goodsQueryInfo,
                productAfterResponse.getTypeOfProduct(), productAfterResponse.getId());
        return RestResult.success(goodsPageQueryResponse);
    }

    /**
     * 平台批量分发商品给商家
     *
     * @return
     */
    @Override
    public RestResult<String> batchPlatformProduct(BatchProductRequest batchProductRequest) {
        // 根据当前类目id查询所有商品
        List<Long> productIds = null;
        if (!batchProductRequest.getCategoryIds().isEmpty()) {
            List<Long> longs = productMapper.queryByCategoryId(batchProductRequest);
            // 合并类目查询商品和已勾选商品并去重
            productIds = Stream.of(longs, batchProductRequest.getProductIds())
                    .flatMap(Collection::stream)
                    .distinct()
                    .collect(Collectors.toList());
        } else {
            productIds = batchProductRequest.getProductIds();
        }

        for (Long productId : productIds) {
            // 查询商品基本信息
            Product product = productMapper.queryByPrimaryKey(productId);
            if (product == null) {
                continue;
            }
            // 调用批量分发方法
            this.batchMerchant(product, batchProductRequest.getMerchantRequestList());
        }
        return RestResult.success("成功");
    }

    /**
     * 商家批量分发商品给店铺
     *
     * @param batchProductRequest
     * @return
     */
    @Override
    public RestResult<String> batchMerchantProduct(BatchProductRequest batchProductRequest) {
        // 根据当前类目id查询所有商品
        List<Long> productIds = null;
        if (batchProductRequest.getCategoryIds().isEmpty()) {
            productIds = batchProductRequest.getProductIds();
        } else {
            List<Long> longs = productMapper.queryByCategoryId(batchProductRequest);
            // 合并类目查询商品和已勾选商品并去重
            productIds = Stream.of(longs, batchProductRequest.getProductIds())
                    .flatMap(Collection::stream)
                    .distinct()
                    .collect(Collectors.toList());
        }

        for (Long productId : productIds) {
            // 查询商品基本信息
            Product product = productMapper.queryByPrimaryKey(productId);
            if (product == null) {
                continue;
            }
            // 调用批量分发方法
            this.batchStore(product, batchProductRequest.getStoreRequestList());
        }
        return RestResult.success("成功");
    }


    /**
     * 封装参数
     *
     * @param goodsInfo
     * @param typeOfProduct
     * @param id
     * @return
     */
    private GoodsPageQueryResponse packagedGoods(GoodsQueryInfo goodsInfo, Integer typeOfProduct,
                                                 long id) {
        GoodsPageQueryResponse goodsPageQueryResponse = new GoodsPageQueryResponse();
        //系列子品信息
        if (typeOfProduct == 2) {
            //根据系列虚品的Id 查询所有子商品
            List<Product> products = productMapper.queryProductByParentId(new Product() {{
                setParentId(id);
            }});
            List<GoodsQueryInfo> skuInfoList = new ArrayList<>();
            //遍历取出系列子品
            products.forEach(product -> {
                //查询商品基本信息
                ProductAfterResponse productAfterResponse = productMapper
                        .queryProductListByProdId(product.getId());

                GoodsQueryInfo goodsQueryInfo = this.encapsulationProduct1(productAfterResponse);
                //根据数组Ids查询所有商品属性名
                List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper.
                        queryPropertyNameById(productAfterResponse.getId());

                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < productPropertyResponseFrontList.size(); i++) {
                    //根据商品属性名ids查询所有商品属性值数据
                    List<ProductPropertyValueResponse> ppv = productMapper.
                            queryPropertyValueById(productPropertyResponseFrontList.get(i).getId());
                    sb.append(productPropertyResponseFrontList.get(i).getName()).
                            append(":").append(ppv.get(0).getValueName()).append(";");
                }
                if (StringUtils.isNotEmpty(sb.toString())) {
                    goodsQueryInfo.setGoodsAttributes(sb.deleteCharAt(sb.length() - 1).toString());
                }
                skuInfoList.add(goodsQueryInfo);
            });
            goodsPageQueryResponse.setSkuInfoList(skuInfoList);
        } else {
            //根据数组Ids查询所有商品属性名
            List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper.
                    queryPropertyNameById(id);

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < productPropertyResponseFrontList.size(); i++) {
                //根据商品属性名ids查询所有商品属性值数据
                List<ProductPropertyValueResponse> ppv = productMapper.
                        queryPropertyValueById(productPropertyResponseFrontList.get(i).getId());
                sb.append(productPropertyResponseFrontList.get(i).getName()).
                        append(":").append(ppv.get(0).getValueName()).append(";");
            }
            if (StringUtils.isNotEmpty(sb.toString())) {
                goodsInfo.setGoodsAttributes(sb.deleteCharAt(sb.length() - 1).toString());
            }
            goodsPageQueryResponse.setSkuInfoList(new ArrayList<>());
        }
        goodsPageQueryResponse.setGoodsInfo(goodsInfo);
        return goodsPageQueryResponse;
    }

    /**
     * 封装商品对象
     *
     * @param productAfterResponse
     */
    private GoodsQueryInfo encapsulationProduct1(ProductAfterResponse productAfterResponse) {
        GoodsQueryInfo goodsQueryInfo = new GoodsQueryInfo();
        goodsQueryInfo.setGoodsName(productAfterResponse.getChineseName());
        goodsQueryInfo.setSalePriceScope(productAfterResponse.getSalePriceWithTax() == null ? "" :
                productAfterResponse.getSalePriceWithTax().toString());
        goodsQueryInfo.setGoodsCategory(productAfterResponse.getFullNamePath());
        goodsQueryInfo.setStock(productAfterResponse.getTotalStock());
        goodsQueryInfo.setDeptId(productAfterResponse.getDeptId());
        goodsQueryInfo.setDeptName(productAfterResponse.getDeptName());
        goodsQueryInfo.setStoreId(productAfterResponse.getStoreId());
        goodsQueryInfo.setStoreName(productAfterResponse.getStoreName());
        goodsQueryInfo.setId(productAfterResponse.getId());
        goodsQueryInfo.setGoodsStatus(productAfterResponse.getCanSale());
        goodsQueryInfo.setMeasureUnit(productAfterResponse.getUnitsName());
        return goodsQueryInfo;
    }


    /**
     * 封装商品对象
     *
     * @param shopInfoResponse
     */
    private GoodsQueryInfo encapsulationProduct2(ShopInfoResponse shopInfoResponse) {
        //主品信息
        GoodsQueryInfo goodsInfo = new GoodsQueryInfo();
        goodsInfo.setGoodsName(shopInfoResponse.getChineseName());
        goodsInfo.setSalePriceScope(shopInfoResponse.getSalePriceWithTax() == null ? "" :
                shopInfoResponse.getSalePriceWithTax().toString());
        goodsInfo.setGoodsCategory(shopInfoResponse.getFullNamePath());
        goodsInfo.setStock(shopInfoResponse.getTotalStock());
        goodsInfo.setDeptId(shopInfoResponse.getDeptId());
        goodsInfo.setDeptName(shopInfoResponse.getDeptName());
        goodsInfo.setStoreId(shopInfoResponse.getStoreId());
        goodsInfo.setStoreName(shopInfoResponse.getStoreName());
        goodsInfo.setId(shopInfoResponse.getId());
        goodsInfo.setGoodsStatus(shopInfoResponse.getCanSale());
        goodsInfo.setMeasureUnit(shopInfoResponse.getProductUnit());
        return goodsInfo;
    }

    /**
     * 商家分发给店铺
     *
     * @param product
     * @param deptId
     */
    @Transactional(rollbackFor = Exception.class)
    public Product saveStore(Product product, Long deptId, Long productId) {

        //添加商品基本信息
        product.setCode(IDUtils.GenerateBillNo("P"));
        Product product1 = this.saveProductInfo(product, deptId);

        //添加保障关联表
        this.saveProductGuaranteeRelation(productId, deptId, product1.getId());

        //添加商品文描 h5 pc
        this.saveProductDescribe(productId, deptId, product1.getId());

        //添加商品售后表
        this.saveProductAfterSale(productId, deptId, product1.getId());

        //添加商品属性名
        this.saveProductPropertyNameRelation(productId, deptId, product1.getId());

        //添加商品销售区域关联表
        this.saveProductSaleAreaRelation(productId, deptId, product1.getId());

        //添加商品图片
        this.saveProductMedia(productId, deptId, product1.getId());

        //添加组合商品
        this.saveProductBom(productId, deptId, product1.getId());

        //添加校标商品
        this.saveProductCalibration(productId, deptId, product1.getId());

        //添加店铺类目
        this.saveCategoryMerchantRelation(product1.getCategoryId(), deptId);

        return product1;
    }


    @Override
    public PageResult<ShopProductInfoResponse> queryShopProductPage(ShopInfoRequest shop, Page pageQuery) {
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<ShopProductInfoResponse> list = productMapper
                .queryShopProductPage(startIndex, pageQuery.getLimit(), shop);
        list.forEach(item -> {
            SysDeptRequest sysDeptRequest = new SysDeptRequest();
            sysDeptRequest.setId(item.getDeptId());
            RestResult<MemStoreResponse> storeInfo = sysDeptApi.getStoreInfoByDeptId(sysDeptRequest);
            if (null != storeInfo && null != storeInfo.getData()) {
                item.setStoreName(storeInfo.getData().getStoreName());
            }
        });
        long count = productMapper.queryShopProductPageCount(shop);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    /**
     * 查询店铺导出商品
     *
     * @param shop
     * @return
     */
    @Override
    public List<ShopInfoResponse> queryShopProductList(ShopInfoRequest shop) {
        return productMapper.queryShopProductList(shop);
    }

    /**
     * 批量分发商家
     *
     * @param product
     * @param merchantRequestList
     */
    private void batchMerchant(Product product, List<MerchantRequest> merchantRequestList) {
        for (int i = 0; i < merchantRequestList.size(); i++) {
            //分发记录表
            ProductDistribute productDistribute = new ProductDistribute();
            productDistribute.setDeptId(merchantRequestList.get(i).getDeptId());
            productDistribute.setProductId(product.getId());
            long count = productDistributeMapper.queryDistributeCount(productDistribute);
            if (count > 0) {
                continue;
            }
            productDistributeService.insert(productDistribute);
            //商品系列子品
            if (product.getTypeOfProduct() == 2) {
                Product product1 = new Product();
                product1.setParentId(product.getId());
                List<Product> products = productMapper.queryProductByParentId(product1);
                //商品来源类型:1-平台;2-商家
                product.setSourceType(1);
                // 分发时商品默认上架
                product.setCanSale(1);
                //商品数据类型:1-运营商品;2-商家商品;3-店铺商品;
//                product.setDataType(2);
                Product p = this.saveMerchantOrStoreId(product, merchantRequestList.get(i).getDeptId(), product.getId());
                for (Product product2 : products) {
                    //初始产品ID
                    Long productId = product2.getId();
                    //保存商品基本信息
                    //商品来源类型:1-平台;2-商家
                    product2.setSourceType(1);
                    //商品数据类型:1-运营商品;2-商家商品;3-店铺商品;
//                    product2.setDataType(2);
                    product2.setParentId(p.getId());
                    product2.setDeptId(merchantRequestList.get(i).getDeptId());
                    product2.setStoreId(null);
                    product2.setTypeOfProduct(3);
                    product2.setCanSale(1);
                    product2.setCode(IDUtils.GenerateBillNo("P"));
                    productMapper.insert(product2);
                    //添加商品价格
                    this.saveProductPrice(productId, merchantRequestList.get(i).getDeptId(), product2.getId());
                    //添加商品属性名
                    this.saveProductPropertyNameRelation(productId, merchantRequestList.get(i).getDeptId(), product2.getId());

                }
            } else {
                //商品来源类型:1-平台;2-商家
                product.setSourceType(1);
                //商品数据类型:1-运营商品;2-商家商品;3-店铺商品;
//                product.setDataType(2);
                this.saveMerchantOrStoreId(product, merchantRequestList.get(i).getDeptId(), product.getId());
            }
        }
    }

    /**
     * description: 批量分发店铺
     *
     * @author: jackHe
     * @time: 2020/4/29 16:52
     */
    private void batchStore(Product product, List<StoreRequest> storeRequestList) {
        for (int i = 0; i < storeRequestList.size(); i++) {
            // 分发记录表
            ProductDistribute productDistribute = new ProductDistribute();
            productDistribute.setStoreId(storeRequestList.get(i).getDeptId());
            productDistribute.setProductId(product.getId());
            long count = productDistributeMapper.queryDistributeCount(productDistribute);
            if (count > 0) {
                continue;
            }
            productDistributeService.insert(productDistribute);

            // 商品系列子品
            if (product.getTypeOfProduct() == 2) {
                Product product1 = new Product();
                product1.setParentId(product.getId());
                List<Product> products = productMapper.queryProductByParentId(product1);
                // 商品来源类型:1-平台;2-商家
                product.setSourceType(2);
                // 分发时商品默认上架
                product.setCanSale(1);
                // 商品数据类型:1-运营商品;2-商家商品;3-店铺商品;
//                product.setDataType(3);
                product.setStoreName(storeRequestList.get(i).getUserName());
                Product p = this.saveMerchantOrStoreId(product, storeRequestList.get(i).getDeptId(), product.getId());
                for (Product product2 : products) {
                    // 初始产品ID
                    Long productId = product2.getId();
                    // 保存商品基本信息
                    // 商品来源类型:1-平台;2-商家
                    product2.setSourceType(2);
                    // 商品数据类型:1-运营商品;2-商家商品;3-店铺商品;
//                    product2.setDataType(3);
                    product2.setParentId(p.getId());
                    product2.setStoreId(storeRequestList.get(i).getDeptId());
                    product2.setTypeOfProduct(1);
                    product2.setCanSale(1);
                    product2.setStoreName(storeRequestList.get(i).getUserName());
                    productMapper.insert(product2);
                    // 添加商品价格
                    this.saveProductPrice(productId, storeRequestList.get(i).getDeptId(), product2.getId());
                    // 添加商品属性名
                    this.saveProductPropertyNameRelation(productId, storeRequestList.get(i).getDeptId(), product2.getId());
                }
            } else {
                // 商品来源类型:1-平台;2-商家
                product.setSourceType(2);
                // 商品数据类型:1-运营商品;2-商家商品;3-店铺商品;
//                product.setDataType(3);
                product.setCanSale(1);
                product.setStoreName(storeRequestList.get(i).getUserName());
                this.saveMerchantOrStoreId(product, storeRequestList.get(i).getDeptId(), product.getId());
            }
        }
    }

    @Override
    public RestResult<PageResult<ProductResponse>> queryProductByCategoryId(ProductRequest productRequest) {
        int startIndex = (productRequest.getStart() - 1) * productRequest.getLimit();
        productRequest.setStart(startIndex);
        // 获取当前类目下一级类目
        List<Category> categories = categoryMapper.queryById(productRequest.getCategoryId());
        List<Category> startList = new ArrayList<>(categories);
        List<Category> endList = new ArrayList<>(categories);
        childCategory(startList, endList);
        PageResult<ProductResponse> pageResult = new PageResult<ProductResponse>();
        List<ProductResponse> result = null;
        long count = 0;
        if (!endList.isEmpty()) {
            result = productMapper.productByCategoryId(endList, productRequest);
            count = productMapper.productByCategoryIdCount(endList, productRequest);
            pageResult.setRows(result);
            pageResult.setTotal(count);
            return RestResult.success(pageResult);
        }
        result = productMapper.productByCategoryId(null, productRequest);
        count = productMapper.productByCategoryIdCount(null, productRequest);
        pageResult.setRows(result);
        pageResult.setTotal(count);
        return RestResult.success(pageResult);
    }

    /**
     * 查询SKU列表
     *
     * @param request
     * @return
     */
    @Override
    public RestResult<PageResult<GoodsQueryInfo>> querySkuPageByPromotionId(GoodsSpuPageQueryRequest request) {
        //计算下标
        int startIndex = (request.getStart() - 1) * request.getLimit();
        ShopInfoRequest shopInfoRequest = new ShopInfoRequest();
        shopInfoRequest.setParentId(request.getSpuId());
        shopInfoRequest.setTypeOfProduct(3);
        shopInfoRequest.setProductCategoryName(request.getGoodsCategory());
        shopInfoRequest.setChineseName(request.getGoodsName());
        shopInfoRequest.setStoreIds(request.getStoreIds());
        //根据系列虚品的Id 查询所有子商品
        List<Product> products = productMapper.queryProductSkuPage(startIndex, request.getLimit(), shopInfoRequest);

        long count = productMapper.queryProductSkuPageCount(shopInfoRequest);
        List<GoodsQueryInfo> skuInfoList = new ArrayList<>();
        //遍历取出系列子品
        products.forEach(product -> {
            //查询商品基本信息
            ProductAfterResponse productAfterResponse = productMapper.queryProductListByProdId(product.getId());

            GoodsQueryInfo goodsQueryInfo = this.encapsulationProduct1(productAfterResponse);
            //根据数组Ids查询所有商品属性名
            List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper.
                    queryPropertyNameById(productAfterResponse.getId());

            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < productPropertyResponseFrontList.size(); i++) {
                //根据商品属性名ids查询所有商品属性值数据
                List<ProductPropertyValueResponse> ppv = productMapper.
                        queryPropertyValueById(productPropertyResponseFrontList.get(i).getId());
                sb.append(productPropertyResponseFrontList.get(i).getName()).
                        append(":").append(ppv.get(0).getValueName()).append(";");
            }
            if (StringUtils.isNotEmpty(sb.toString())) {
                goodsQueryInfo.setGoodsAttributes(sb.deleteCharAt(sb.length() - 1).toString());
            }
            skuInfoList.add(goodsQueryInfo);
        });
        PageResult<GoodsQueryInfo> pageResult = new PageResult<>();
        pageResult.setRows(skuInfoList);
        pageResult.setTotal(count);
        return RestResult.success(pageResult);
    }

    @Override
    public List<Product> queryAll(Product product) {
        return productMapper.queryAll(product);
    }

    /**
     * 冻结库存
     *
     * @param mStoreFrozenRequest
     * @return
     */
    @Override
    public RestResult<Boolean> frozenStock(MStoreFrozenRequest mStoreFrozenRequest) {
        //判断是否校标款
        StoreInventory storeInventory = storeInventoryMapper.queryByProductId(mStoreFrozenRequest.getProductId());
        if (storeInventory != null) {
            log.info("购买数量:{}", mStoreFrozenRequest.getApplyNum());
            log.info("可用库存:{}", storeInventory.getAvailableStock());
            if (mStoreFrozenRequest.isFrozenFlag()) {
                storeInventory.setAvailableStock(storeInventory.getAvailableStock() - mStoreFrozenRequest.getApplyNum().intValue() == 0 ? 0 : storeInventory.getAvailableStock() - mStoreFrozenRequest.getApplyNum().intValue());
                storeInventory.setProductId(mStoreFrozenRequest.getProductId());
                storeInventory.setUpdateTime(new Date());
                storeInventoryMapper.update(storeInventory);
            } else {
                storeInventory.setAvailableStock(storeInventory.getAvailableStock() + mStoreFrozenRequest.getApplyNum().intValue());
                storeInventory.setProductId(mStoreFrozenRequest.getProductId());
                storeInventory.setUpdateTime(new Date());
                storeInventoryMapper.update(storeInventory);
            }
        }
        return RestResult.success(Boolean.TRUE);
    }


    public void childCategory(List<Category> startList, List<Category> endList) {
        for (Category category : startList) {
            List<Category> categoriesOne = new ArrayList<>();
            List<Category> categoriesTwo = new ArrayList<>();
            if (category.getIsLeaves() == 2) {
                categoriesOne = categoryMapper.queryById(category.getId());

                for (Category category1 : categoriesOne) {
                    if (category.getId() == category1.getParentId()) {
                        categoriesTwo.add(category1);
                    }
                }

                if (categoriesTwo.size() > 0) {
                    endList.addAll(categoriesTwo);
                    childCategory(categoriesTwo, endList);
                }
                continue;
            }
        }
    }


    /**
     * 根据产品父id查询产品信息
     *
     * @param productId
     * @return
     */
    @Override
    public RestResult<List<ProductAfterInfoByIdResponse>> queryProductInfoByParentId(Long productId) {
        return RestResult.success(productBomMapper.queryProductInfoByParentId(productId));
    }

    @Override
    public PageResult<ShopInfoResponse> queryPorductByStoreId(Product product, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        Long deptId = product.getDeptId();
        List<ShopInfoResponse> list = productMapper.queryPorductByStoreId(startIndex, pageQuery.getLimit(), deptId);
        long count = productMapper.queryPageCountByStoreId(deptId);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public PageResult<List<ProductResponseFront>> queryRestPorduct(ProductRestRequest productRestRequest) {
        //计算下标
        int startIndex = (productRestRequest.getStart() - 1) * productRestRequest.getLimit();
        List<ProductResponseFront> list = new ArrayList<>();
        PageResult pageResult = new PageResult();
        //查询前台类目聚合的后台类目id 和 前台类目直接聚合的商品id
        List<Long> categoryIds = new ArrayList<>();
        if (productRestRequest.getCategoryId() != null) {
            categoryIds = categoryTreeNodeRelationMapper.queryByRestLeftTreeNodeId(Long.valueOf(productRestRequest.getCategoryId()));
            CategoryTreeNodeProduct categoryTreeNodeProduct = new CategoryTreeNodeProduct();
            categoryTreeNodeProduct.setLeftTreeNodeId(Long.valueOf(productRestRequest.getCategoryId()));
            List<Long> proIds = categoryTreeNodeProductMapper.queryProductId(categoryTreeNodeProduct);
            if (CollectionUtils.isEmpty(categoryIds) && CollectionUtils.isEmpty(proIds)) {
                pageResult.setRows(list);
                pageResult.setTotal(0);
                return pageResult;
            }
            productRestRequest.setCategoryIds(categoryIds);
            productRestRequest.setProductIds(proIds);
        }
        // 根据促销id查询活动商品列表
        List<Long> promotionGoodIds = Lists.newArrayList();
        if (StringUtils.isNotEmpty(productRestRequest.getPromotionId()) && productRestRequest.getPromotionType() != null){
            // 查询促销活动商品列表
            RestResult<PromotionPolymericResponse> promotionPolymericResponseRestResult = marketApi.queryPromotionProduct(
                    new PromotionPolymericRequest(){{
                        setPromotionId(productRestRequest.getPromotionId());
                        setPromotionType(productRestRequest.getPromotionType());
                    }});

            if (promotionPolymericResponseRestResult != null && promotionPolymericResponseRestResult.getData() != null
                    && !CollectionUtils.isEmpty(promotionPolymericResponseRestResult.getData().getProductResponses())){
                promotionGoodIds = promotionPolymericResponseRestResult.getData().getProductResponses().stream()
                        .map(PromotionPolymericProductResponse::getMpId).collect(Collectors.toList());
                productRestRequest.setProductIds(promotionGoodIds);
            }
        }
        //排序 1 代表综合 2 代表价格最高 3 代表价格最低 4代表评价最多 5代表销量 6代表新品
        list = productMapper.queryRestPorduct(productRestRequest, startIndex, productRestRequest.getLimit());
        list.forEach(item -> {
//            List<String> codes = new ArrayList<>();
//            codes.add(item.getCode());
//            RealTimePriceRequest realTimePriceRequest = new RealTimePriceRequest();
//            realTimePriceRequest.setThirdProductCodes(codes);
//            RestResult<RealTimePriceListResponse> priceStockList = realTimePriceRestApi.getPriceStockList(realTimePriceRequest);
//            if (null != priceStockList && null != priceStockList.getData() && CollectionUtils.isNotEmpty(priceStockList.getData().getRealTimePrices()) && !priceStockList.getData().getRealTimePrices().get(0).getAvailablePrice().equals("")) {
//                item.setMarketPrice(priceStockList.getData().getRealTimePrices().get(0).getAvailablePrice());
//            } else {
//                item.setMarketPrice(String.valueOf(item.getSalePriceWithTax().intValue()));
//            }
            item.setMarketPrice(item.getSalePriceWithTax());
        });

        Long count = productMapper.queryRestPorductCount(productRestRequest);
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }


    @Override
    public List<ProductStoreInfo> queryProductByStoreIds(Product product) {
        return productMapper.queryProductByStoreIds(product);
    }

    @Override
    public List<ProductStoreInfo> queryProductBySpuId(Product product) {
        return productMapper.queryProductBySpuId(product);
    }

    @Override
    public List<ProductStoreInfo> queryProductBySpuList(GoodsPageQueryRequest goodsPageQueryRequest) {
        List<ProductStoreInfo> list = productMapper.queryProductBySpuList(goodsPageQueryRequest);
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(item -> {
                List<SysDeptResponse> deptList = sysDeptApi.query(new SysDeptRequest() {{
                    setId(item.getDeptId());
                }});
                if (CollectionUtils.isNotEmpty(deptList)) {
                    item.setStoreId(deptList.get(0).getBusinessId());
                    item.setStoreName(deptList.get(0).getDeptName());
                    List<SysDeptResponse> pDeptList = sysDeptApi.query(new SysDeptRequest() {{
                        setId(deptList.get(0).getPid());
                    }});
                    if (CollectionUtils.isNotEmpty(pDeptList)) {
                        item.setDeptId(pDeptList.get(0).getBusinessId());
                        item.setDeptName(pDeptList.get(0).getDeptName());
                    }
                }
            });
            list.forEach(productInfo -> {
                Product product = new Product();
                product.setParentId(productInfo.getId());
                List<ProductStoreInfo> list1 = productMapper.queryProductByStoreIds(product);
                list1.forEach(item -> {
                    List<SysDeptResponse> deptList = sysDeptApi.query(new SysDeptRequest() {{
                        setId(item.getDeptId());
                    }});
                    if (CollectionUtils.isNotEmpty(deptList)) {
                        item.setStoreId(deptList.get(0).getBusinessId());
                        item.setStoreName(deptList.get(0).getDeptName());
                        List<SysDeptResponse> pDeptList = sysDeptApi.query(new SysDeptRequest() {{
                            setId(deptList.get(0).getPid());
                        }});
                        if (CollectionUtils.isNotEmpty(pDeptList)) {
                            item.setDeptId(pDeptList.get(0).getBusinessId());
                            item.setDeptName(pDeptList.get(0).getDeptName());
                        }
                    }
                });
                productInfo.setChildren(list1);
            });
        }
        return list;
    }

    @Override
    public List<Long> queryProductByCode(GoodsPageQueryRequest goodsPageQueryRequest) {
        return productMapper.queryProductByCode(goodsPageQueryRequest);
    }

    @Override
    public List<ProductStoreInfo> queryProductBySpuIds(List<Long> spuIds, Integer canle) {
        List<ProductStoreInfo> list = productMapper.queryProductBySpuIds(spuIds, canle);
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(item -> {
                List<SysDeptResponse> deptList = sysDeptApi.query(new SysDeptRequest() {{
                    setId(item.getDeptId());
                }});
                if (CollectionUtils.isNotEmpty(deptList)) {
                    item.setStoreId(deptList.get(0).getBusinessId());
                    item.setStoreName(deptList.get(0).getDeptName());
                    List<SysDeptResponse> pDeptList = sysDeptApi.query(new SysDeptRequest() {{
                        setId(deptList.get(0).getPid());
                    }});
                    if (CollectionUtils.isNotEmpty(pDeptList)) {
                        item.setDeptId(pDeptList.get(0).getBusinessId());
                        item.setDeptName(pDeptList.get(0).getDeptName());
                    }
                }
                Product product = new Product();
                product.setParentId(item.getId());
                List<ProductStoreInfo> list1 = productMapper.queryProductBySpuId(product);

                list1.forEach(item1 -> {
                    List<SysDeptResponse> deptChildList = sysDeptApi.query(new SysDeptRequest() {{
                        setId(item1.getDeptId());
                    }});
                    if (CollectionUtils.isNotEmpty(deptChildList)) {
                        item1.setStoreId(deptChildList.get(0).getBusinessId());
                        item1.setStoreName(deptChildList.get(0).getDeptName());
                        List<SysDeptResponse> pDeptList = sysDeptApi.query(new SysDeptRequest() {{
                            setId(deptChildList.get(0).getPid());
                        }});
                        if (CollectionUtils.isNotEmpty(pDeptList)) {
                            item1.setDeptId(pDeptList.get(0).getBusinessId());
                            item1.setDeptName(pDeptList.get(0).getDeptName());
                        }
                    }
                });
                item.setChildren(list1);

            });
        }
        return list;
    }

    @Override
    public List<ProductStoreInfo> queryProductListByThirdProductCodes(String codeList) {
        return productMapper.queryProductListByThirdProductCodes(codeList);
    }

    @Override
    public PageResult<ProductStoreInfo> queryProductPageByStoreIds(GoodsPageQueryRequest goodsPageQueryRequest, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<ProductStoreInfo> list = productMapper.queryProductPageByStoreIds(goodsPageQueryRequest, startIndex, pageQuery.getLimit());
        long count = productMapper.queryProductPageByStoreIdsCount(goodsPageQueryRequest);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    /**
     * 根据商品id查询商品规格
     *
     * @param productId
     * @return
     */
    @Override
    public List<ProductPropertyResponse> queryPropertyNameByProductId(Long productId) {
        List<ProductPropertyResponse> productPropertyResponseList = new ArrayList<>();
        List<ProductPropertyResponseFront> productPropertyResponseFrontList = productMapper.queryPropertyNameById(productId);
        for (ProductPropertyResponseFront productPropertyResponseFront : productPropertyResponseFrontList) {
            ProductPropertyResponse productPropertyResponse = new ProductPropertyResponse();
            productPropertyResponse.setAttrId(productPropertyResponseFront.getAttNameId());
            productPropertyResponse.setAttrName(productPropertyResponseFront.getName());
            //根据商品属性名id查询所有商品属性值数据
            List<ProductPropertyValueResponse> ppv = productMapper.queryPropertyValueById(productPropertyResponseFront.getId());
            if (CollectionUtils.isNotEmpty(ppv)) {
                productPropertyResponse.setValueId(ppv.get(0).getValueId());
                productPropertyResponse.setValueName(ppv.get(0).getValueName());
                productPropertyResponseList.add(productPropertyResponse);
            }
        }
        return productPropertyResponseList;
    }

    @Override
    public Boolean updateProductSaleNum(ProductSaleNumRequest productSaleNumRequest) {
        try {
            log.info("开始进入更新商品销售数量============》》" + productSaleNumRequest.toString());
            if (CollectionUtils.isNotEmpty(productSaleNumRequest.getProductSaleNumRequestList())) {
                productSaleNumRequest.getProductSaleNumRequestList().forEach(item -> {
                    Product product = productMapper.queryByPrimaryKey(item.getProductId());
                    if (null != product) {
                        if (item.getSaleNum() == null) {
                            item.setSaleNum(product.getSaleNum());
                        } else {
                            item.setSaleNum(product.getSaleNum() + item.getSaleNum());
                        }
                    }
                });
                productMapper.updateProductSaleNum(productSaleNumRequest);
                return Boolean.TRUE;
            } else {
                return Boolean.FALSE;
            }
        } catch (Exception e) {
            log.error("更新商品销售数量===============》", e);
            return Boolean.FALSE;
        }
    }

    @Override
    public List<ProductStoreInfo> queryProductListBySpuId(Long spuId) {
        List<ProductStoreInfo> list = new ArrayList<>();
        Product product = new Product();
        product.setParentId(spuId);
        List<Product> products = productMapper.query(product);
        products.forEach(product1 -> {
            ProductStoreInfo productStoreInfo = new ProductStoreInfo();
            BeanUtils.copyProperties(product1, productStoreInfo);
            list.add(productStoreInfo);
        });
        return list;
    }

    @Override
    public RestResult<List<ProductInfoResponse>> queryGoodsByType(ProductDetailRequest request) {
        if (request.getType() == null){
            log.error("商品类型参数为空");
            return RestResult.error("9999","商品类型参数为空");
        }
        // 根据类型查询商品列表
        List<ProductInfoResponse> productInfoResponses = productMapper.queryGoodsByType(request);
        if (CollectionUtils.isEmpty(productInfoResponses)){
            log.info("根据类型查询商品列表为空,type:{}",request.getType());
            return RestResult.success(Lists.newArrayList());
        }
        return RestResult.success(productInfoResponses);
    }

    @Override
    public List<ProductResponse> queryBySupplierCode(String supplierCode) {
        return productMapper.queryBySupplierCode(supplierCode);
    }

}
